import * as React from 'react';
import { Col, Row, Menu, Carousel } from 'antd'
import Pubsub from 'pubsub-js'

import Advert from '../../components/Advert/Advert';
import ArticleList from '../../components/ArticleList/ArticleList';
import { reqArticles, reqCarousels } from '../../axios';
import Personal from '../../components/Personal/Personal';
import './Home.less'
interface Icarousel {
  id: number
  cover: string
  name: string
  orderNum: number
  addr: string
}
export interface HomeProps {

}
export interface article {
  article: {
    id: number
    summary: string
    read: number
    createTime: string
    isOriginal: number
    title: string
    isTop: number
    cover: string
    categoryId: number
    oppose: number
    support: number
  }
  tags: [
    { content: string, id: number }
  ]
  category: { name: string }


}
export interface HomeState {
  articles: article[]
  carousels: Icarousel[]
  clickCount: number
  articlesCount: number
  isAll: Boolean

}

class Home extends React.PureComponent<HomeProps, HomeState> {
  img: any
  orderBy: string = 'create_time' //根据哪个字段排序
  state = {
    articles: [],
    carousels: [
      {
        id: 0,
        cover: '',
        name: '',
        orderNum: 0,
        addr: '',
      }
    ],
    clickCount: 0,
    articlesCount: 0,
    isAll: false, // 是否是全部文章列表用来判断是否显示加载更多按钮,

  }
  async componentDidMount() {
    //注册订阅信息
    Pubsub.subscribe('clickCount', () => {
      //统计一下点击加载更多按钮的次数 为显示条数做准备
      this.setState({ clickCount: ++this.state.clickCount }, () => {
        this.handleOrder(this.orderBy, 'desc');
      })
    })
    //请求文章信息 排序
    this.handleOrder('create_time', 'desc');
    //请求轮播图信息
    const carouselResponse = await reqCarousels({});
    if (carouselResponse.data.success) {
      this.setState({ carousels: carouselResponse.data.data.records });
    }
  }
  componentWillUnmount() {
    PubSub.unsubscribe('clickCount')
  }
  //请求文章列表
   handleOrder = async (field: string, order: string, pageNum = 1, pageSize = 4) => {
    try {
      const response = await reqArticles({ pageNum: pageNum + this.state.clickCount, pageSize, orderEntity: { 'is_top': 'asc', [field]: order } });
      if (response.data.success) {
        const articles = response.data.data.records;
        //记录文章的总数        
        this.setState({ articlesCount: response.data.data.total }, () => {
          if (this.state.articlesCount <= (pageNum + this.state.clickCount) * pageSize) {
            this.setState({ isAll: true })
          }
        })
        //对文章数组进行修改
        if (this.state.clickCount === 0) {
          this.setState({ articles })
        } else {
          //加载更多
          this.setState((state) => ({
            articles: [...state.articles, ...articles]
          }))
        }
      }
    } catch (error) {
      console.log(error);
    }
  }
  render() {
    const { articles, carousels } = this.state;
    const contentStyle = {
      height: '400px',
      width: '900px',
      color: '#fff',
      lineHeight: '160px',
      textAlign: 'center',
      background: '#364d79',
    };

    const header = (
      <Menu mode='horizontal'>
        <Menu.Item onClick={() => { this.setState({ clickCount: 0, isAll: false }, () => { this.handleOrder('create_time', 'desc'); this.orderBy = 'create_time' }) }}>
          最新
        </Menu.Item>
        <Menu.Item onClick={() => { this.setState({ clickCount: 0, isAll: false }, () => { this.handleOrder('read', 'desc'); this.orderBy = 'read'; }) }}>
          热门
        </Menu.Item>
      </Menu>
    )
    return (
      <>
        <div className='home-center'>
          <div className='home-top-bg' >
            {/* <img src={require('./imgs/headerBg2.png').default} alt="banner"/> */}
          </div>
          <div className='home-center-left'>
            <span className='btn-left' onClick={() => this.img.prev()}>&lt;</span><span className='btn-right' onClick={() => this.img.next()}>&gt;</span>
            <Carousel autoplay ref={dom => this.img = dom}>
              {
                carousels.map(carousel => {
                  return (
                    <div key={carousel.id}>
                      <a href={carousel.addr} target="_blank" rel="noopener noreferrer">
                        {/* @ts-ignore */}
                        <img style={contentStyle} src={carousel.cover} alt={carousel.name} />
                      </a>
                    </div>
                  )
                })
              }
            </Carousel>
          </div>
          <div className='home-center-right'>
            <div className='right-img1'><a target='_blank' rel="noopener noreferrer" href="https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_3" >a</a></div>
            <div className='right-img2'><a target='_blank' rel="noopener noreferrer" href="http://www.baidu.com">a</a></div>
          </div>
        </div>
        <div className='home-main'>
          <Row justify='center'>
            <Col className='home-main-left' xs={24} sm={24} md={24} lg={18} xl={18}>
              <ArticleList isAll={this.state.isAll} header={header} articles={articles}></ArticleList>
            </Col>
            <Col className='home-main-right' xs={0} sm={0} md={0} lg={6} xl={6}>
              <Personal></Personal>
              <Advert></Advert>
            </Col>
          </Row>
        </div>
      </>);
  }
}

export default Home;